<template><div>
    <AdminLayout
            :left-fixed="true"
            no-sel-message="请选择公司或部门再进行操作~"
            ref="adminLayout"
        >
            <template #left>
                <div style="height: 100%;" >
                    <SideTree
                        ref="sideTreeRef"
                        @searchAllData="searchAllData"
                        @selectTree="selectTree"
                        @SuccessfuCallbackFn="SuccessfuCallbackFn"
                        @handNameFn="handNameFn" 
                        @createFolder="parentChang" 
                        @handleTreeDelete="handleTreeDelete" 
                        @handleTreeMove="handleTreeMove" />
                </div> 
            </template>
            <main class="page admin-page page-container detail-page video-page">
                <div class="page-title">
                    <div class="left">
                        <span class="btn-back" @click="$router.back()"></span>
                        <div class="title" @click="$router.back()">{{ liveMsg.title }}</div>
                    </div>
                    <div class="right-option">
                        <div class="option-item">
                            <i class="e-column"></i>
                            <span>编目</span>
                        </div>
                    </div>
                </div>
    <div class="video-block">
        <div class="outBox">
            <div class="editBox">
                <div class="leftEditBox updateScroollStyle" ref="countref">
                    <div class="showVideoBox">
                        <div class="liveBox">
                            <div class="showVideoItem" :style="{ height: `${showItemHeight}px` }">
                                <div id="player_contarn1"></div>
                            </div>
                            <div class="live-controls">
                                <div class="live-item-title">
                                    <span>视频预览</span><span>{{ currentTime }}</span>
                                </div>
                                <img v-if="!playStatus" src="../../assets/img/live/play.png" class="playIcon" alt="" @click="videoPlayHandle" />
                                <img v-else src="../../assets/img/live/stop.png" class="playIcon" alt="" @click="videoStopHandle" />
                                <div class="live-item-volume1"></div>
                            </div>
                        </div>
                    </div>
                    <div class="actionBox">
                        <div class="toolBox">
                            <ul class="sub-menu">
                                <li 
                                 v-for="item in tabMenu"
                                 :key="item.id"
                                 :class="{active: tabActive == item.id}"
                                 @click="switchTab(item.id)" 
                                 >{{ item.name }}
                                 <span v-if="item.id == 2">({{ cutVideoList.length }})</span>
                                 <span v-if="item.id == 3">({{ shearVideoList.length }})</span>
                                </li>
                            </ul>
                            <div v-show="tabActive == 1" class="toolCenterBox">
                                <div v-if="isVideo" class="toolLeftBox" @click="getTqHandle">
                                    <img src="../../assets/img/live/cut-edit.png" alt="" />
                                    <span>添加关键帧</span>
                                </div>
                                <div v-if="isVideo" class="setingBox setingBox1" @click="upDataVideoHandle('1')">
                                    <img src="../../assets/img/live/icon_video.png" alt="" />
                                    <span>截取拆条</span>
                                </div>
                                <div class="setingBox setingBox1" @click="upDataVideoHandle('2')">
                                    <img src="../../assets/img/live/icon_audio.png" alt="" />
                                    <span>获取音频</span>
                                </div>
                            </div>
                            <!-- <div v-show="tabActive" class="live-item-volume">
                                <i class="icon-cyt" @click="timeCytHandle('jian')"></i>
                                <a-slider :max="5" :min="1" @afterChange="onTimeCy" class="volume-slider slider11" v-model:value="timeWidth" :tooltip-visible="false" />
                                <i class="icon-cyt1" @click="timeCytHandle('jia')"></i>
                            </div> -->
                            <div>&nbsp;</div>
                            <a-button
                             v-show="tabActive == 2" 
                             type="primary"
                             :disabled="is_status" 
                             @click="submitCut" 
                             style="padding: 0 12px;">
                                开始拆条
                            </a-button>
                        </div>
                        <div v-show="tabActive == 1">
                            <div class="timeSetBox">
                                <div class="setingBox setingBox-first" @click="settingStartTimeHandle">
                                    <img src="../../assets/img/live/start.png" alt="" />
                                    <span>设置入点</span>
                                </div>
                                <span>入点：</span>
                                <a-input-number :controls="false" class="numIpt" @blur="numberChange('startH')" v-model:value="Times.startH" :min="0" :max="24" />
                                <span>时</span>
                                <a-input-number :controls="false" class="numIpt" @blur="numberChange('startM')" v-model:value="Times.startM" :min="0" :max="59" />
                                <span>分</span>
                                <a-input-number :controls="false" class="numIpt" @blur="numberChange('startS')" v-model:value="Times.startS" :min="0" :max="59" />
                                <span>秒</span>
                                <span class="chudian">出点：</span>
                                <a-input-number :controls="false" class="numIpt" @blur="numberChange('endH')" v-model:value="Times.endH" :min="0" :max="24" />
                                <span>时</span>
                                <a-input-number :controls="false" class="numIpt" @blur="numberChange('endM')" v-model:value="Times.endM" :min="0" :max="59" />
                                <span>分</span>
                                <a-input-number :controls="false" class="numIpt" @blur="numberChange('endS')" v-model:value="Times.endS" :min="0" :max="59" />
                                <span>秒</span>
                                <div class="setingBox" @click="settingEndTimeHandle">
                                    <img src="../../assets/img/live/end.png" alt="" />
                                    <span>设置出点</span>
                                </div>
                            </div>

                            <!--时间线  -->
                            <div class="tracksBox updateScroollStyle" ref="scrollEle">
                                <div class="trackInBox" :style="{ width: `${timeLIneWidth}px` }">
                                    <div class="imgTimes" ref="targetEle">
                                        <div v-for="(item, index) in imgList" :key="item.time">
                                            <div class="imgTimeship" @click="seekerHandle1(item.time, index)" v-show="(index * 2) % timeRate == 0"></div>
                                        </div>
                                    </div>
                                    <div class="timelinePanel" :style="{ width: `${timeLIneWidth}px` }">
                                        <div class="scale" v-for="(item, index) in imgList" attr-time="item.time" :key="item.time">
                                            <div v-show="index % timeRate == 0" class="scaleed">
                                                <div class="timeS">{{ parseTime(item.time, '{h}:{i}:{s}') }}</div>
                                                <div class="scales">
                                                    <i v-for="(it, i) in 10" :key="i"></i>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="timeShowBox" :style="{ width: `${timeLIneWidth}px` }">
                                            <div v-show="typeof setTime.startTime == 'number'" class="startChip" :class="setTime.endTime ? 'startChipAll' : ''" :style="{ left: `${setTime.startTime - 6}px`, width: `${setTime.width ? setTime.width + 12 : 0}px` }">
                                                <div v-show="setTime.endTime" class="inTimes"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mediaTrackContainer">
                                        <div class="clippedAreaLeft" :class="setTime.endTime ? 'clippedArea' : ''" :style="{ left: `${setTime.startTime}px`, width: `${setTime.width}px` }" v-show="typeof setTime.startTime == 'number'"></div>
                                        <!-- <virtual-list :data-key="'time'" :data-sources="imgList" :data-component="ImgItem" /> -->
                                        <div v-for="(item, index) in imgList" :key="item.time"><img class="imgItem" :src="encodeURI1(item.url)" alt="" :style="{marginRight: liveMsg.main_type == 2 ? '5px': '0', width: liveMsg.main_type == 2 ? '100px': '105px'}" /></div>
                                    </div>
                                    <div class="tqBox" :style="{ width: `${timeLIneWidth}px` }">
                                        <img v-for="(item, index) in zhenList" :key="index" :class="item.left ? 'showImg' : ''" src="../../assets/img/live/qp.png" alt="" :style="{ left: `${item.left / masks[timeWidth]}px` }" />
                                    </div>
                                    <div class="seeker" @mousedown="mousedownHandle" :style="{ left: `${timeLInesLeft}px` }">
                                        <div class="head"></div>
                                        <div class="tail"></div>
                                    </div>
                                    <!-- 这里是拖动出入点的地方 -->
                                    <div class="clippedAreaDargBox" v-show="setTime.endTime" @mousedown="mousedownCliped" :style="{ left: `${setTime.startTime}px` }"></div>
                                    <div class="clippedAreaDargBox" v-show="setTime.endTime" @mousedown="mousedownClipedEnd" :style="{ left: `${setTime.endTime - 4}px` }"></div>
                                </div>
                            </div>
                        </div>
                        <ul v-show="tabActive == 2" class="video-list">
                            <li v-for="(item, idx) in cutVideoList" :key="idx" class="video-item">
                                <div class="video-chaitiao">
                                    <div :style="{backgroundImage: `url('${encodeURI1(item.img)}')`}" class="video-chai" />
                                    <div class="title-tips">
                                        <span>{{ parseTime(flagTime + item.seek_start * 1000, '{h}:{i}:{s}') }}-{{ parseTime(flagTime + item.seek_end * 1000, '{h}:{i}:{s}') }}</span>
                                        <img src="@/assets/img/live/close-chai.png" @click="handleCutDelete(idx)">
                                    </div>
                                </div>
                                <p class="chai">{{ item.name }}</p>
                                <a-input class="chai" v-model:value="item.name" />
                            </li>
                        </ul>
                        <ul v-show="tabActive == 3" class="video-list chai-list">
                            <li
                             v-for="(item, idx) in shearVideoList" 
                             :key="item.id" 
                             class="video-item"
                             @click="handleShearNav(item.media_resource_id)">
                                <div class="video-chaitiao">
                                    <div :style="{backgroundImage: `url('${encodeURI1(item.thumbnail)}')`}" class="video-chai" />
                                    <div class="title-tips">
                                        <span>&nbsp;</span>
                                        <span>{{item.main_type == 2 ? '视频': '音频'}}</span>
                                    </div>
                                </div>
                                <p>{{ parseTime(item.created_at, '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
                                <p>{{ item.title }}</p>
                            </li>
                        </ul>
                    </div>
                </div>
                <!-- 菜单 -->
                <div :class="zankai ? 'rightTab zankai' : 'rightTab'">
                    <img v-if="!zankai" class="sousuozankaiBtn" @click="showCHouti" src="@/assets/img/home2.0/zankai.png" alt="" />
                    <img v-if="zankai" class="sousuozankaiBtn" @click="showCHouti" src="@/assets/img/home2.0/sousuo.png" alt="" />
                    <div class="gongnengxuanxiang">
                        <LiveSetting
                         v-if="liveMsg.main_type"
                         ref="liveSettingEle" 
                         :duration="durationMsg" 
                         :item-obj="rightTabData" 
                         :liveId="liveId" 
                         :type="liveMsg.main_type" 
                         :zhenList="zhenList" 
                         :pdList="pdList" 
                         @deleteZhen="deleteZhen" 
                         @foucsTime="foucsTime" 
                         @foucsShotTime="foucsShotTime" 
                         @deletePd="deletePd" 
                         @textByTime="textByTime"
                         @seekFace="faceSeeker" />
                    </div>
                    <section class="rightTabBtn" :style="{ borderColor: zankai ? '#EBEEF5' : 'transparent' }">
                        <div
                         v-for="(item, index) in rightTabFn"
                         @click="rightTabIndexHandle(index, item)" 
                         :class="rightTabIndex == item.icon ? 'checked' : ''">
                            <img :src="getIcon(item.icon, index)" alt="" />
                            <p>
                                {{ item.text }}
                            </p>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>
</main>
</AdminLayout>
</div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect, nextTick, onBeforeUnmount } from 'vue';
import SideTree from "../MediaIndex/components/SideTree.vue";
import AdminLayout from "@/components/AdminLayout/AdminLayout.vue";
import { useRouter, useRoute } from 'vue-router';
import { LeftOutlined } from '@ant-design/icons-vue';
import { useUserStore } from '@/store/user';
import { throttle } from 'lodash-es';
import { useWindowSize, useMouseInElement, useScroll } from '@vueuse/core';
import { searchSnapshotList, deleteLiveEdit, getIndex } from '@/utils/api-utils';
import dayjs from 'dayjs';
import LiveSetting from './LiveSetting.vue';
import { message } from 'ant-design-vue';
import { parseTime, getTimeDuration } from '../../utils/index';
import { 
    mediaInfo, 
    cutAudioVideo, 
    keyFrameList, 
    addFrame, 
    deleteFrame, 
    shotAnalysis,
    getChildMediaList
} from '@/utils/audioVideo';
import { useFileInfoStore } from "@/store/fileInfo";
import { useGlobalStore } from "@/store/global";
import { encodeURI1 } from "@/utils/global"

const useGlobal = useGlobalStore();
const useFileInfo = useFileInfoStore();
const { width } = useWindowSize();
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const zankai = ref(false);
const countref = ref<any>(null);
const liveSettingEle = ref<any>(null);
const targetEle = ref<any>(null);
const scrollEle = ref<any>(null);
const zhenList = ref<any>([]);
const pdList = ref<any>([]);
const liveId = ref<any>('');
const isVideo = ref<boolean>(true);
const isSmall = ref<boolean>(false);
const rightTabIndex = ref('n0');
const rightTabData = ref({ text: '镜头分析', icon: 'n0' });
let rightTabFn = [
    { text: '镜头分析', icon: 'n0' },
    { text: '人脸分析', icon: 'n1' },
    { text: '语音分析', icon: 'n3' },
    { text: '图文分析', icon: 'n4' },
    { text: '关键帧', icon: 'n2' }
];
const playStatus = ref(false);
const micWidth = ref(30);
const voiceBool = ref(0);
const timeWidth = ref<number>(5);
const timeOldWidth = ref(5);
const oldrate = ref<any>(1);
const masks: any = {
    1: 50,
    2: 20,
    3: 10,
    4: 5,
    5: 1
};
const timeRate = ref(2);
const Times = ref<any>({ startH: '00', startM: '00', startS: '00', endH: '00', endM: '00', endS: '00' });
const setTime = ref<any>({ startTime: '', start: '', end: '', endTime: '', width: 0 });
const imgList = ref<any>([]);
const timeLIneWidth = ref(0);
const timeLInesLeft = ref(-5);
const { elementX, isOutside } = useMouseInElement(targetEle);
const { x } = useScroll(scrollEle, { behavior: 'smooth' });
const showItemHeight = ref(0);
const videoLive1 = ref<any>(null);
const videoLive = ref<any>(null);
const timeSnap = ref<any>(null);
const currentTimes = ref<any>(null);
const zhiboUrlTIme = ref<any>(null);
const currentTime = ref<any>('00:00:00');
const liveMsg = ref<any>({});
const preTime = ref<any>('');
const acur = ref<any>('');
const snapshotObj = ref<any>({ liveId: '', pic: '', time: '' });
const lvboUrl = ref<any>('');
const isFristSeek = ref(true);
const tabActive = ref<number>(1);
const tabMenu = ref<any[]>([
    {
        id: 1,
        name: '音视频处理'
    },
    {
        id: 2,
        name: '拆条队列'
    },
    {
        id: 3,
        name: '已拆条列表'
    }
]);
const flagTime = ref<number>(Date.parse(parseTime(Date.now(), '{y}-{m}-{d}') +' 00:00:00'));
const durationMsg = ref<number>(0);
const imgShotList = ref<any>([]);
const cutVideoList = ref<any>([]);
const shearVideoList = ref<any>([]);
const is_status = ref<boolean>(false);
const sideTreeRef = ref();
// status:1:未直播 2：直播中 3：已结束
onMounted(() => {
    liveId.value = route.query.id || '';
    if (liveId.value) {
        //获取直播详情
        getLiveDetailHandle();
        //剪辑片段
        getFrameListHandle();
        getShearList();
    }
});

onBeforeUnmount(() => {
    clearInterval(timeSnap.value);
    timeSnap.value = null;
    if (currentTimes.value) {
        clearInterval(currentTimes.value);
        currentTimes.value = null;
        console.log('清除计时器');
    }
    if (videoLive.value) {
        console.log('销毁播放器');

        videoLive.value.dispose();
        videoLive.value = null;
    }
    if (videoLive1.value) {
        console.log('销毁播放器1');
        videoLive1.value.dispose();
        videoLive1.value = null;
    }
    clearInterval(zhiboUrlTIme.value);
    zhiboUrlTIme.value = null;
});

// 已拆条队列
const getShearList = () => {
    getChildMediaList({
        id: liveId.value
    }).then(res => {
        shearVideoList.value = res.data.result.data;
    }).catch(error => {
        console.log(error);
    });
    // shearList(liveId.value).then(res => {
    //     console.log(res.data.result.data);
    //     shearVideoList.value = res.data.result.data;
    // }).catch(err => console.log(err));
}

const handleShearNav = (id: string) => {
    router.push(`/admin/mediaDetails?id=${id}`);
}

const getLiveDetailHandle = async () => {
    mediaInfo(liveId.value).then(res => {
        liveMsg.value = res.data.result.data;
        liveMsg.value.playUrl = res.data.result.data.url;
        isVideo.value = res.data.result.data.main_type == 2 ? true : false;
        durationMsg.value = Number(res.data.result.data.duration);
        currentTime.value = getTimeDuration(Number(res.data.result.data.duration));
        // 获取本地操作拆条
        const temp = localStorage.getItem('cutList');
        let localCut = [];
        if (temp) {
            const tempArr = JSON.parse(temp);
            localCut = tempArr.localCutList;
        }
        let arr = [];
        for(let i in localCut) {
            if (localCut[i].time + 7 * 24 * 3600 > Date.now()) {
                arr.push(localCut[i]);
                if(localCut[i].media_id == liveId.value) {
                    cutVideoList.value = localCut[i].list;
                }
            }
        }
        useFileInfo.setLocalCutList(arr);

        if (!isVideo.value) {
            rightTabData.value = { text: '语音分析', icon: 'n3' };
            rightTabFn = [{ text: '语音分析', icon: 'n3' }];
            rightTabIndex.value = 'n3';
        }

        if (liveMsg.value.main_type == 2) {
            getEditLiveListHandle();
            window.addEventListener('scroll', handleScrollShot, true);
        }

        initVideo();
        searchSnapshotListHandle();
    });
};
const switchTab = (data: boolean) => {
    tabActive.value = data;
}

const getFrameListHandle = () => {
    keyFrameList({ id: liveId.value })
        .then((res: any) => {
            console.log('查询关键帧');
            console.log(res);
            if (res.data.status_code == 1 && res.data.result.data.length) {
                let tempArr = [];
                for (let i in res.data.result.data) {
                    tempArr.push({
                        pic: res.data.result.data[i].url,
                        time: Number(res.data.result.data[i].time_line_point) * 1000 + flagTime.value
                    });
                }
                console.log(tempArr)
                zhenList.value = [...tempArr];
                zhenListmap();
            }
        })
        .catch((err: any) => {
            console.log(err);
        });
};
const zhenListmap = () => {
    //处理帧的位置left
    for (let index = 0; index < zhenList.value.length; index++) {
        //查看图片是否在列表中
        const i = imgList.value.findIndex((item: any) => item.url === zhenList.value[index].pic);
        console.log(i, index);
        if (i > -1) {
            let timeCha = zhenList.value[index].time - imgList.value[i].time;
            console.log(timeCha);
            //获取时间差
            let i1 = i + 1;
            console.log(i);
            let timeShip = imgList.value[i1].time - imgList.value[i].time;
            let curr = Math.round((timeCha * 105) / timeShip);
            let left = curr + 105 * i - 5;
            console.log(left);
            zhenList.value[index].left = left;
        }
    }
};
const timeListHandle = () => {
    timeLIneWidth.value = Math.ceil(imgList.value.length / timeRate.value) * 210;
};
const mousedownHandle = (e: any) => {
    let target = e.target;
    console.log(target);
    while (!target.classList.contains('seeker')) {
        target = target.parentNode;
    }
    // console.log(target);
    // console.log('elementX.value');
    // console.log(elementX.value);

    function handlerMove(e: any) {
        // console.log('按钮移动中');

        if (!isOutside.value) {
            timeLInesLeft.value = elementX.value - 5;
            // console.log(timeLInesLeft.value);
            let num = Math.floor(elementX.value / 105) * masks[timeWidth.value];
            // console.log(num);
            let time = imgList.value[num].time;
            seekerHandle1(time, num, timeLInesLeft.value * masks[timeWidth.value]);
        } else {
            // if (elementX.value < 0) {
            //     timeLInesLeft.value = -5;
            // }
            document.removeEventListener('mousemove', handlerMove);
            document.removeEventListener('mouseup', handlerUp);
        }
    }
    function handlerUp(e: any) {
        let num = Math.floor(elementX.value / 105) * masks[timeWidth.value];
        // console.log(num);
        let time = imgList.value[num].time;
        seekerHandle1(time, num, timeLInesLeft.value * masks[timeWidth.value]);
        document.removeEventListener('mousemove', handlerMove);
        document.removeEventListener('mouseup', handlerUp);
    }
    document.addEventListener('mousemove', handlerMove);
    document.addEventListener('mouseup', handlerUp);
};

const getIndexHandle = () => {
    let obj = { liveId: liveId.value };
    getIndex(obj)
        .then((res: any) => {
            console.log('直播实时链接');
            console.log(res);
            if (res.data) {
                lvboUrl.value = res.data;
                if (videoLive1.value) {
                    console.log('已初始化视频，不作操作');
                } else {
                    initVideo();
                }
            } else {
                message.warning('暂未生成预览视频链接，请稍后重试！');
            }
        })
        .catch();
};
const initVideo = () => {
    videoLive1.value = new Aliplayer(
        {
            id: 'player_contarn1',
            source: encodeURI1(liveMsg.value.playUrl),
            width: '100%',
            height: '100%',
            autoplay: false,
            isLive: false,
            rePlay: false,
            playsinline: false,
            isVBR: true,
            preload: true,
            controlBarVisibility: 'always',
            useH5Prism: true,
            skinLayout: [
                {
                    name: 'H5Loading',
                    align: 'cc'
                },
                {
                    name: 'errorDisplay',
                    align: 'tlabs',
                    x: 0,
                    y: 0
                },
                {
                    name: 'infoDisplay'
                },
                {
                    name: 'tooltip',
                    align: 'blabs',
                    x: 0,
                    y: 56
                },
                {
                    name: 'thumbnail'
                },
                {
                    name: 'controlBar',
                    align: 'blabs',
                    x: 0,
                    y: 0,
                    children: [
                        {
                            name: 'progress',
                            align: 'blabs',
                            x: 0,
                            y: 44
                        },
                        {
                            name: 'playButton',
                            align: 'tl',
                            x: 15,
                            y: 12
                        },
                        {
                            name: 'timeDisplay',
                            align: 'tl',
                            x: 10,
                            y: 7
                        },
                        {
                            name: 'fullScreenButton',
                            align: 'tr',
                            x: 10,
                            y: 12
                        },
                        {
                            name: 'subtitle',
                            align: 'tr',
                            x: 15,
                            y: 12
                        },
                        {
                            name: 'setting',
                            align: 'tr',
                            x: 15,
                            y: 12
                        },
                        {
                            name: 'volume',
                            align: 'tr',
                            x: 5,
                            y: 10
                        }
                    ]
                }
            ]
        },
        function (player) {
            console.log('The player is created');
            player.on('ready', async function () {
                if (liveMsg.value.type == 1 && isFristSeek.value) {
                    isFristSeek.value = false;
                    setTimeout(() => {
                        player.seek(0);
                    }, 2000);
                }
            });
            player.on('ended', async function () {
                console.log('播放结束');
                videoStopHandle();
                if (liveMsg.value.type == 1) {
                    await player.loadByUrl(lvboUrl.value.indexUrl);
                    setCurrentHandle();
                    // videoPlayHandle();
                } else {
                    acur.value = imgList.value[0].time;
                    currentTime.value = parseTime(acur.value, '{h}:{i}:{s}');
                }
            });
        }
    );
};
const faceSeeker = (timeSeek:string) => {
    videoLive1.value.seek(timeSeek);
};
const setCurrentHandle = () => {
    // TODO 这里是否需要设置seek?
    let timeSeek = Math.round((acur.value - imgList.value[0].time) / 1000) || 0;
    console.log(timeSeek);
    videoLive1.value.seek(timeSeek);
};
const videoPlayHandle = () => {
    let tag = false;
    playStatus.value = true;
    if (currentTimes.value) {
        clearInterval(currentTimes.value);
        currentTimes.value = null;
        console.log('清除计时器');
    }
    if (!acur.value) { acur.value = Date.parse(parseTime(Date.now(), '{y}-{m}-{d}') +' 00:00:00'); }
    currentTimes.value = setInterval(() => {
        if (!tag) {
            videoLive1.value.play();
            tag = true;
        }
        acur.value = acur.value + 1000;
        currentTime.value = parseTime(acur.value, '{h}:{i}:{s}');
        console.log(currentTime.value);
    }, 1000);
};
const videoStopHandle = () => {
    videoLive1.value.pause();
    playStatus.value = false;
    if (currentTimes.value) {
        clearInterval(currentTimes.value);
        currentTimes.value = null;
        console.log('清除计时器');
    }
};

//查询图片
const searchSnapshotListHandle = () => {
    let timeNowStr = parseTime(Date.now(), '{y}-{m}-{d}') +' '+ currentTime.value;
    flagTime.value = Date.parse(parseTime(Date.now(), '{y}-{m}-{d}') +' 00:00:00');
    let secondNum = 5; // 以5秒分隔
    let Num = Math.floor(Number(parseTime(new Date(timeNowStr), '{h}')) * 3600 / secondNum + Number(parseTime(new Date(timeNowStr), '{i}')) * 60 / secondNum + Number(parseTime(new Date(timeNowStr), '{s}')) / secondNum);
    let count = Math.floor(Number(durationMsg.value));
    const startPoint = liveMsg.value.start_point;
    const keyName = !liveMsg.value.father_oss_key?
                    liveMsg.value.oss_key.slice(0, liveMsg.value.oss_key.lastIndexOf('.')) :
                    liveMsg.value.father_oss_key.slice(0, liveMsg.value.father_oss_key.lastIndexOf('.'));
    const fileName = !liveMsg.value.father_file_name? 
                    liveMsg.value.file_name.slice(0, liveMsg.value.file_name.lastIndexOf('.'))
                    :liveMsg.value.father_file_name.slice(0, liveMsg.value.father_file_name.lastIndexOf('.'));
    
    // 音频
    const audioImg = [new URL("@/assets/img/live/1.jpg", import.meta.url).href,
    new URL("@/assets/img/live/2.jpg", import.meta.url).href,
    new URL("@/assets/img/live/3.jpg", import.meta.url).href,
    new URL("@/assets/img/live/4.jpg", import.meta.url).href];
    let countImg = 0;
    let countShot = 0;
    // 镜头分析使用
    for (let i = 0; i < count; i++) {
        if (liveMsg.value.main_type == 3) {
            if (countShot % 4 == 0) countShot = 0;
            imgShotList.value.push({
                status: true,
                url: audioImg[countShot],
                time: flagTime.value + i * 1000
            });
            countShot ++;
        } else {
            imgShotList.value.push({
                status: true,
                url: !liveMsg.value.frame_url_template ? `${useGlobal.HOST}/auth/redir?key=${keyName}/${fileName}-${i+1+Number(startPoint)}.png_frame` : `${liveMsg.value.frame_url_template}-${i+1+Number(startPoint)}.png_frame`,
                time: flagTime.value + i * 1000
            });
        }
    }
    // 拉取对应图片
    for (let i = 0; i < Num; i++) {
        if (liveMsg.value.main_type == 3) {
            if (countImg % 4 == 0) countImg = 0;
            imgList.value.push({
                status: true,
                url: audioImg[countImg],
                time: flagTime.value + i * secondNum * 1000
            });
            countImg ++;
        } else {
            imgList.value.push({
                url: !liveMsg.value.frame_url_template ? `${useGlobal.HOST}/auth/redir?key=${keyName}/${fileName}-${Number(startPoint)+i*secondNum+1}.png_frame` : `${liveMsg.value.frame_url_template}-${Number(startPoint)+i*secondNum+1}.png_frame`,
                time: flagTime.value + i * secondNum * 1000
            });
        }
    }
    console.log('#######');
    console.log(count, Num, imgList.value.length, imgShotList.value.length);


    // 如果末尾不在5s
    imgList.value[imgList.value.length - 1] = imgShotList.value[imgShotList.value.length - 1];
    if (Num == 1) imgList.value[0] = imgShotList.value[0];
    timeListHandle();
    // timeSnapHandle();
};
const timeSnapHandle = () => {
    if (timeSnap.value) {
        clearInterval(timeSnap.value);
        timeSnap.value = null;
        console.log('清除图片计时器');
    }
    timeSnap.value = setInterval(() => {
        if (imgList.value.length) {
            preTime.value = imgList.value[imgList.value.length - 1].time;
        }
        let obj = { liveId: liveId.value, preTime: preTime.value, count: 40, type: 2 };
        searchSnapshotList(obj)
            .then((res: any) => {
                // console.log('截图');
                // console.log(res);
                if (res.code == 1 && res.data.length) {
                    imgList.value = [...imgList.value, ...res.data];
                    timeListHandle();
                }
            })
            .catch((err: any) => {
                console.log(err);
            });
    }, 5000);
};
const backHome = () => {
    router.push('/live');
};
const onAfterChange = (value: number) => {
    console.log('afterChange: ', value);
    videoLive.value.setVolume(micWidth.value / 100);
};

const seekerHandleShot = throttle(async (time: any, index: any, left?: any, zhenTime?: any) => {
    // console.log(index);
    // console.log(time);
    let oldTimeLInesLeft = timeLInesLeft.value;
    //获取时间差
    let i = index + masks[timeWidth.value];
    // console.log(i);
    if (!imgShotList.value[index]) {
        message.info('此处时间正在生成中，请稍等！');
        return;
    }
    if (!isOutside.value) {
        timeLInesLeft.value = elementX.value - 5;
    } else if (elementX.value < 0) {
        timeLInesLeft.value = -5;
    }
    // console.log(left);
    if (typeof left == 'number') {
        //((left+ 5) *  oldrate.value) / masks[timeWidth.value] - 5
        if (left == 0) {
            timeLInesLeft.value = -5;
        } else {
            timeLInesLeft.value = left / masks[timeWidth.value];
        }
    }
    // console.log('滚动距离');
    // console.log(x.value);
    if (timeLInesLeft.value > 420) {
        x.value = timeLInesLeft.value - 400;
    } else {
        x.value = 0;
    }

    //获取当前区间段位移
    let cha = timeLInesLeft.value + 5 - (105 * index) / masks[timeWidth.value];
    // console.log(cha);

    let timeShip = imgShotList.value[i].time - time;
    let curr = Math.round((cha * timeShip) / 105);
    acur.value = time + curr;
    if (zhenTime) {
        acur.value = zhenTime;
    }
    videoStopHandle();
    currentTime.value = parseTime(acur.value, '{h}:{i}:{s}');
    let timeSeek = Math.round((acur.value - imgShotList.value[0].time) / 1000) || 0;
    if (liveMsg.value.type == 1) {
        let allTime = videoLive1.value.getDuration();
        console.log(allTime);
        if (allTime < timeSeek) {
            await videoLive1.value.loadByUrl(lvboUrl.value.indexUrl);
            timeLInesLeft.value = oldTimeLInesLeft;
            message.warning('该时间还在加载中请稍后重试');
            return;
        }
    }
    videoLive1.value.seek(timeSeek);
}, 20);

const seekerHandle1 = throttle(async (time: any, index: any, left?: any, zhenTime?: any) => {
    // console.log(index);
    // console.log(time);
    let oldTimeLInesLeft = timeLInesLeft.value;
    //获取时间差
    let i = index + masks[timeWidth.value];
    // console.log(i);
    if (!imgList.value[index]) {
        message.info('此处时间正在生成中，请稍等！');
        return;
    }
    if (!isOutside.value) {
        timeLInesLeft.value = elementX.value - 5;
    } else if (elementX.value < 0) {
        timeLInesLeft.value = -5;
    }
    // console.log(left);
    if (typeof left == 'number') {
        //((left+ 5) *  oldrate.value) / masks[timeWidth.value] - 5
        if (left == 0) {
            timeLInesLeft.value = -5;
        } else {
            timeLInesLeft.value = left / masks[timeWidth.value];
        }
    }
    // console.log('滚动距离');
    // console.log(x.value);
    if (timeLInesLeft.value > 420) {
        x.value = timeLInesLeft.value - 400;
    } else {
        x.value = 0;
    }

    //获取当前区间段位移
    let cha = timeLInesLeft.value + 5 - (105 * index) / masks[timeWidth.value];
    // console.log(cha);
    
    let timeShip = (i > imgList.value.length - 1) ?  imgList.value[imgList.value.length - 1].time - time : imgList.value[i].time - time;
    let curr = Math.round((cha * timeShip) / 105);
    acur.value = time + curr;
    if (zhenTime) {
        acur.value = zhenTime;
    }
    videoStopHandle();
    currentTime.value = parseTime(acur.value, '{h}:{i}:{s}');
    let timeSeek = Math.round((acur.value - imgList.value[0].time) / 1000) || 0;
    if (liveMsg.value.type == 1) {
        let allTime = videoLive1.value.getDuration();
        console.log(allTime);
        if (allTime < timeSeek) {
            await videoLive1.value.loadByUrl(lvboUrl.value.indexUrl);
            timeLInesLeft.value = oldTimeLInesLeft;
            message.warning('该时间还在加载中请稍后重试');
            return;
        }
    }
    videoLive1.value.seek(timeSeek);
    snapshotObj.value.liveId = liveId.value;
    snapshotObj.value.pic = imgList.value[index].url;
    snapshotObj.value.time = acur.value;
}, 20);
const voiceHandle = () => {
    if (voiceBool.value) {
        micWidth.value = voiceBool.value;
        voiceBool.value = 0;
    } else {
        voiceBool.value = micWidth.value;
        micWidth.value = 0;
    }
    console.log(voiceBool.value);
    videoLive.value.setVolume(micWidth.value / 100);
};
const onTimeCy = (value: number) => {
    //初始化设置出入点
    initSetTime();
    oldrate.value = masks[timeOldWidth.value];
    timeRate.value = masks[timeWidth.value] * 2;
    //重新处理图片展示和时间轴
    timeListHandle();
    if (timeLInesLeft.value == -5) {
        return;
    }

    timeLInesLeft.value = ((timeLInesLeft.value + 5) * oldrate.value) / masks[timeWidth.value] - 5;
    if (timeLInesLeft.value < -5) {
        timeLInesLeft.value = -4;
    }
    nextTick(() => {
        if (timeLInesLeft.value > 420) {
            x.value = timeLInesLeft.value - 400;
        } else {
            x.value = 0;
        }
    });
    timeOldWidth.value = timeWidth.value;
};
const timeCytHandle = (key: string) => {
    //初始化设置出入点
    oldrate.value = masks[timeWidth.value];
    initSetTime();
    if (key == 'jian' && timeWidth.value > 1) {
        timeWidth.value -= 1;
    }
    if (key == 'jia' && timeWidth.value < 5) {
        timeWidth.value += 1;
    }

    timeRate.value = masks[timeWidth.value] * 2;
    //重新处理图片展示和时间轴
    timeListHandle();
    if (timeLInesLeft.value == -5) {
        return;
    }
    console.log(timeWidth.value);

    timeLInesLeft.value = ((timeLInesLeft.value + 5) * oldrate.value) / masks[timeWidth.value] - 5;
    if (timeLInesLeft.value < -5) {
        timeLInesLeft.value = -4;
    }
    nextTick(() => {
        if (timeLInesLeft.value > 420) {
            x.value = timeLInesLeft.value - 400;
        } else {
            x.value = 0;
        }
    });

    timeOldWidth.value = timeWidth.value;
};

const getTqHandle = () => {
    if (snapshotObj.value.url == '') {
        message.info('请选择关键帧！');
        return;
    }
    getFrameListHandle();
    addFrame({
        id: liveId.value,
        url: snapshotObj.value.pic,
        time_line_point: (snapshotObj.value.time - flagTime.value)/1000
    })
        .then((res: any) => {
            if (res.data.status_code == 1) {
                message.success('添加成功！');
                getFrameListHandle();
            }
        })
        .catch();
};
const deleteZhen = (index: number) => {
    let obj = { 
        id: liveId.value, 
        url: zhenList.value[index].pic,
        time_line_point: (zhenList.value[index].time - flagTime.value)/1000
    };
    deleteFrame(obj)
        .then((res: any) => {
            console.log(res);
            if (res.data.status_code == 1) {
                message.success('移除成功！');
                zhenList.value.splice(index, 1);
            }
        })
        .catch();
};

const foucsShotTime = (data: any) => {
    Times.value = { startH: '00', startM: '00', startS: '00', endH: '00', endM: '00', endS: '00' };
    setTime.value = { startTime: '', start: '', end: '', endTime: '', width: 0 };

    const index = data.index;
    setTime.value.startTime = flagTime.value + data.start * 1000;
    console.log(data);
    //查看图片是否在列表中
    const i = imgShotList.value.findIndex((item: any) => item.url === pdList.value[index].key_frame_url);
    console.log(i);
    if (i > -1) {
        //获取left
        let timeCha = Number(pdList.value[index].start) * 1000 + flagTime.value - imgShotList.value[i].time;
        console.log(timeCha);
        //获取时间差
        let i1 = i + 1;
        console.log(i);
        let timeShip = imgShotList.value[i1].time - imgShotList.value[i].time;
        let curr = Math.round((timeCha * 105) / timeShip);
        let left = curr + 105 * i - 5;
        console.log(left);
        pdList.value[index].left = left;
        seekerHandleShot(imgShotList.value[i].time, i, (i-1) * 105 / 5, Number(pdList.value[index].start) * 1000 + flagTime.value);
    } else {
        message.info('该镜头不在此刻时间轴内！');
    }
    settingStartTimeHandle();
    setTimeout(() => {
        setTime.value.endTime = flagTime.value + data.end * 1000;
        currentTime.value = parseTime(setTime.value.endTime, '{h}:{i}:{s}');
        timeLInesLeft.value = 21 * (data.end).toFixed(0);
        if (setTime.value.start <= 0) timeLInesLeft.value = 21 * (data.end).toFixed(0) - 21;
        settingEndTimeHandle();
        setTime.value.end = data.end;
    }, 500);
};

const foucsTime = (index: number) => {
    //查看图片是否在列表中
    const i = imgList.value.findIndex((item: any) => item.url === zhenList.value[index].pic);
    console.log(i);
    if (i > -1) {
        console.log(zhenList.value[index].left);
        if (zhenList.value[index].left) {
            seekerHandle1(imgList.value[i].time, i, zhenList.value[index].left, zhenList.value[index].time);
        } else {
            //获取left
            let timeCha = zhenList.value[index].time - imgList.value[i].time;
            console.log(timeCha);
            //获取时间差
            let i1 = i + 1;
            console.log(i);
            let timeShip = imgList.value[i1].time - imgList.value[i].time;
            let curr = Math.round((timeCha * 105) / timeShip);
            let left = curr + 105 * i - 5;
            console.log(left);
            zhenList.value[index].left = left;
            seekerHandle1(imgList.value[i].time, i, zhenList.value[index].left, zhenList.value[index].time);
        }
    } else {
        message.info('该关键帧不在此刻时间轴内！');
    }
};
const textByTime = (time: any) => {
    console.log(time);
    let times = dayjs(time).valueOf();
    console.log(times);
    //查看对应时间戳是否在列表中
    const ni = imgShotList.value.findIndex((item: any) => item.time >= times);
    console.log(ni);
    let i = ni - 1;

    if (i > -1) {
        //获取left
        let timeCha = times - imgShotList.value[i].time;
        console.log(timeCha);
        //获取时间差
        let i1 = i + 1;
        console.log(i);
        let timeShip = imgShotList.value[i1].time - imgShotList.value[i].time;
        let curr = Math.round((timeCha * 105) / timeShip);
        let left = curr + 105 * i - 5;
        seekerHandleShot(imgShotList.value[i].time, i, (i-1) * 105 / 5, times);
    } else if (i == -1 && times == imgShotList.value[0].time) {
        seekerHandleShot(imgShotList.value[0].time, 0, 0);
    } else {
        message.info('该文字记录不在此刻时间轴内！');
    }
    //清除
    userStore.changeTextInfo({});
};
const mousedownCliped = () => {
    async function handlerMove(e: any) {
        // console.log('按钮移动中');

        if (!isOutside.value) {
            setTimeHandle();
        } else {
            document.removeEventListener('mousemove', handlerMove);
            document.removeEventListener('mouseup', handlerUp);
        }
    }
    async function handlerUp(e: any) {
        setTimeHandle();
        document.removeEventListener('mousemove', handlerMove);
        document.removeEventListener('mouseup', handlerUp);
    }
    document.addEventListener('mousemove', handlerMove);
    document.addEventListener('mouseup', handlerUp);
};
const mousedownClipedEnd = () => {
    async function handlerMove(e: any) {
        // console.log('按钮移动中');
        if (!isOutside.value) {
            setTimeHandleEnd();
        } else {
            document.removeEventListener('mousemove', handlerMove);
            document.removeEventListener('mouseup', handlerUp);
        }
    }
    async function handlerUp(e: any) {
        setTimeHandleEnd();
        document.removeEventListener('mousemove', handlerMove);
        document.removeEventListener('mouseup', handlerUp);
    }
    document.addEventListener('mousemove', handlerMove);
    document.addEventListener('mouseup', handlerUp);
};

const setTimeHandle = async () => {
    if (elementX.value > setTime.value.endTime - 8) {
        setTime.value.startTime = setTime.value.endTime - 8;
        setTime.value.width = 0;
    } else {
        setTime.value.startTime = elementX.value;
        setTime.value.width = setTime.value.endTime - setTime.value.startTime;
    }
    let num = Math.floor(elementX.value / 105) * masks[timeWidth.value];
    // console.log(num);
    let time = imgList.value[num].time;
    await seekerHandle1(time, num, elementX.value * masks[timeWidth.value]);
    //这里处理时间
    setTime.value.start = Math.round((acur.value - imgList.value[0].time) / 1000);
    Times.value.startH = currentTime.value.split(':')[0];
    Times.value.startM = currentTime.value.split(':')[1];
    Times.value.startS = currentTime.value.split(':')[2];
    console.log(setTime.value.start);
};
const setTimeHandleEnd = async () => {
    if (elementX.value < setTime.value.startTime) {
        setTime.value.endTime = setTime.value.startTime + 8;
        setTime.value.width = 0;
    } else {
        setTime.value.endTime = elementX.value;
        setTime.value.width = setTime.value.endTime - setTime.value.startTime;
    }
    let num = Math.floor(elementX.value / 105) * masks[timeWidth.value];
    // console.log(num);
    let time = imgList.value[num].time;
    await seekerHandle1(time, num, elementX.value * masks[timeWidth.value]);
    //这里处理时间
    setTime.value.end = Math.round((acur.value - imgList.value[0].time) / 1000);
    Times.value.endH = currentTime.value.split(':')[0];
    Times.value.endM = currentTime.value.split(':')[1];
    Times.value.endS = currentTime.value.split(':')[2];
    console.log(setTime.value.end);
};
const settingStartTimeHandle = () => {
    let newTime = timeLInesLeft.value + 5;
    if (newTime <= 0) {
        // message.info('入点必须大于0！');
        // return;
        newTime = 0;
    }
    if (newTime > setTime.value.endTime) {
        setTime.value.endTime = '';
        setTime.value.width = 0;
    }
    if (setTime.value.endTime) {
        setTime.value.width = setTime.value.endTime - newTime;
        // if (Times.value.endS > 0 || Times.value.endM > 0 || Times.value.endH > 0) return;
    }
    setTime.value.startTime = newTime;
    
    setTime.value.start = Math.round((acur.value - imgList.value[0].time) / 1000);
    Times.value.startH = currentTime.value.split(':')[0];
    Times.value.startM = currentTime.value.split(':')[1];
    Times.value.startS = currentTime.value.split(':')[2];
    console.log(setTime.value.start);
    console.log(setTime.value.startTime);
};
const settingEndTimeHandle = () => {
    let newTime = timeLInesLeft.value + 5;
    if (setTime.value.startTime < 0) {
        message.info('请设置入点！');
        return;
    }
    if (setTime.value.startTime > newTime) {
        message.info('设置出点不能低于入点！');
        return;
    }
    setTime.value.width = newTime - setTime.value.startTime;
    setTime.value.endTime = newTime;
    setTime.value.end = Math.round((acur.value - imgList.value[0].time) / 1000);
    Times.value.endH = currentTime.value.split(':')[0];
    Times.value.endM = currentTime.value.split(':')[1];
    Times.value.endS = currentTime.value.split(':')[2];
    console.log(setTime.value.end);
    console.log(setTime.value.endTime);
};

const upDataVideoHandle = (data: string = '1') => {
    const keyName = liveMsg.value.oss_key.slice(0, liveMsg.value.oss_key.lastIndexOf('.'));
    const fileName = liveMsg.value.file_name.slice(0, liveMsg.value.file_name.lastIndexOf('.'));
    console.log(typeof setTime.value.startTime !== 'number');
    if (typeof setTime.value.startTime !== 'number') {
        message.info('请设置入点！');
        return;
    }
    if (setTime.value.endTime <= 0) {
        message.info('请设置出点！');
        return;
    }
    if (setTime.value.width == 0) {
        message.info('出入点不能相同！');
        return;
    }

    let prams = { 
        media_id: liveId.value, 
        seek_start: setTime.value.start, 
        seek_end: setTime.value.end, 
        duration: setTime.value.end - setTime.value.start, 
        save_type: data == '1' ? 'video' : 'audio',
        name: `拆条${cutVideoList.value.length + 1}`,
        source_name: liveMsg.value.file_name,
        img: data == '1' ? `${useGlobal.HOST}/auth/redir?key=${keyName}/${fileName}-${setTime.value.start}.png_frame` : new URL("@/assets/img/meadiaIndex/audio-cover.png", import.meta.url).href
    };

    let cutFlag = false;
    for (let i in cutVideoList.value) {
        if (cutVideoList.value[i].seek_start == prams.seek_start 
            && cutVideoList.value[i].seek_end == prams.seek_end
            && cutVideoList.value[i].save_type == prams.save_type
        ) {
            cutFlag = true;
            break;
        }
    }
    if (cutFlag) {
        message.info('该段视频已存在！');
        return;
    }
    cutVideoList.value.push(prams);

    let allArr = useFileInfo.localCutList || [];
    let flag = false;
    for (let i in allArr) {
        if (allArr[i].media_id == prams.media_id) {
            allArr[i].list = cutVideoList.value;
            flag = true;
            break; 
        }
    }
    if (!flag) {
        allArr.push({ 
            media_id: prams.media_id, 
            time: Date.now(),
            list: cutVideoList.value
        });
    }

    useFileInfo.setLocalCutList(allArr);
    message.success('截取拆条成功!');
}

const handleCutDelete = (index: string | number) => {
    let arr = [];
    for (let i in cutVideoList.value) {
        if (i == index) continue;
        arr.push(cutVideoList.value[i]);
    }
    cutVideoList.value = arr;

    let allArr = useFileInfo.localCutList || [];
    for (let i in allArr) {
        if (allArr[i].media_id == liveId.value) {
            allArr[i].list = cutVideoList.value;
            break; 
        }
    }

    useFileInfo.setLocalCutList(allArr);
}

const submitCut = () => {
    if (cutVideoList.value.length < 10) is_status.value = true;
    cutAudioVideo({
        media_id: liveId.value,
        source_name: liveMsg.value.oss_key,
        list: JSON.stringify(cutVideoList.value)
    })
        .then((res: any) => {
            if (res.data.status_code == 1) {
                message.success({ content: '已上传数据，正在处理中。。。', key: 'updatableing', duration: 1 });

                let allArr = useFileInfo.localCutList || [];
                let arr = [];
                for (let i in allArr) {
                    if (allArr[i].media_id == liveId.value) continue;
                    arr.push(allArr[i]);
                }

                useFileInfo.setLocalCutList(arr);
                cutVideoList.value = [];
                is_status.value = false;
            }
        })
        .catch();
};

// 镜头分析
const shotLastId = ref<number | string>('');
const shotLoading = ref(false);
const pageFlag = ref<boolean>(false);
const getEditLiveListHandle = () => {
    let prams = {
        id: liveId.value, 
        lastId: shotLastId.value
    };
    shotAnalysis(prams)
        .then((res: any) => {
            shotLoading.value = false;
            if (res.data.result.data.length < 10) {
                shotLoading.value = true;
                if (pageFlag.value) return;
                pdList.value = pdList.value.concat(res.data.result.data);
                pageFlag.value = true;
                return;
            }
            pdList.value = pdList.value.concat(res.data.result.data);
            shotLastId.value = pdList.value.length - 1;
        })
        .catch();
};

const handleScrollShot = () => {
  const container = document.querySelector('.shot-box');
  if (!container) return;
  const { scrollTop, scrollHeight, clientHeight } = container // 获取滚动高度和内容高度
  if (scrollTop + clientHeight >= scrollHeight && !shotLoading.value) {
    getEditLiveListHandle();
  }
}

const initSetTime = () => {
    setTime.value.width = 0;
    setTime.value.startTime = '';
    setTime.value.start = '';
    setTime.value.endTime = '';
    setTime.value.end = '';
    Times.value.startH = '0';
    Times.value.startM = '0';
    Times.value.startS = '0';
    Times.value.endH = '0';
    Times.value.endM = '0';
    Times.value.endS = '0';
};
const numberChange = (keys: string) => {
    console.log(keys);
    if (Times.value[keys] == null) {
        Times.value[keys] = 0;
    }
    let isStart = keys.includes('start');
    let newsDate = isStart ? Times.value.startH + ':' + Times.value.startM + ':' + Times.value.startS : Times.value.endH + ':' + Times.value.endM + ':' + Times.value.endS;
    let initTime = imgShotList.value[0].time;
    let endIngTime = imgShotList.value[imgShotList.value.length - 1].time;

    let date = parseTime(initTime, '{y}-{m}-{d}');
    console.log(initTime);
    console.log(date);
    console.log(newsDate);
    console.log(date + ' ' + newsDate);
    let timenewShip = dayjs(date + ' ' + newsDate).valueOf();
    console.log(timenewShip);
    if (initTime >= timenewShip) {
        message.warning({ content: '设置出入点不低于时间轴初始值!', key: 'updatableing', duration: 1 });
        return;
    }
    if (timenewShip > endIngTime) {
        message.warning({ content: '设置出入点不高于时间轴最大值!', key: 'updatableing', duration: 1 });
        return;
    }
    if (isStart) {
        textByTime(parseTime(timenewShip));
        timeLInesLeft.value = (timenewShip - flagTime.value)/1000 * 21 - 5;
        settingStartTimeHandle();
    } else {
        if (setTime.value.startTime <= 0) {
            Times.value.endS = 0;
            Times.value.endM = 0;
            Times.value.endH = 0;
            message.warning({ content: '请先设置入点!', key: 'updatableing', duration: 1 });
            return;
        } else if (setTime.value.startTime >= timenewShip / 1000) {
            message.warning({ content: '设置出点不能低于入点!', key: 'updatableing', duration: 1 });
            return;
        } else {
            console.log('zhe-------------');
            textByTime(parseTime(timenewShip));
            timeLInesLeft.value = (timenewShip - flagTime.value)/1000 * 21 - 5;
            settingEndTimeHandle();
        }
    }
};
const deletePd = (index: number) => {
    let obj = { ids: pdList.value[index].id };
    deleteLiveEdit(obj)
        .then((res: any) => {
            console.log(res);
            pdList.value.splice(index, 1);
        })
        .catch();
};
const showCHouti = () => {
    zankai.value = !zankai.value;
    isSmallHandle();
};
const rightTabIndexHandle = (index: any, item: any) => {
    rightTabData.value = item;
    rightTabIndex.value = item.icon;
    zankai.value = true;
    //本场片段时，再次查询生成情况
    if (index == 3) {
        let i = pdList.value.findIndex((item: any) => item.status == 1);
        if (i > -1) {
            getEditLiveListHandle();
        }
    }
    isSmallHandle();
};
function getIcon(icon: string, index: number) {
    const imgHash = {
        "n0": {
            active: new URL("@/assets/img/live/n0_1.png", import.meta.url).href,
            normal: new URL("@/assets/img/live/n0.png", import.meta.url).href
        },
        "n1": {
            active: new URL("@/assets/img/live/n1_1.png", import.meta.url).href,
            normal: new URL("@/assets/img/live/n1.png", import.meta.url).href
        },
        "n2": {
            active: new URL("@/assets/img/live/n2_1.png", import.meta.url).href,
            normal: new URL("@/assets/img/live/n2.png", import.meta.url).href
        },
        "n3": {
            active: new URL("@/assets/img/live/n3_1.png", import.meta.url).href,
            normal: new URL("@/assets/img/live/n3.png", import.meta.url).href
        },
        "n4": {
            active: new URL("@/assets/img/live/n4_1.png", import.meta.url).href,
            normal: new URL("@/assets/img/live/n4.png", import.meta.url).href
        }
    };
    if (rightTabIndex.value === icon) {
        return imgHash[icon].active;
    }
    return imgHash[icon].normal;
}
const isSmallHandle = () => {
    setTimeout(() => {
        let abb = countref.value.offsetWidth;
        console.log(abb);
        if (abb && abb < 712) {
            isSmall.value = true;
        } else {
            isSmall.value = false;
        }
        showItemHeight.value = 400;//showVideoItemEle.value.clientHeight;
        // console.log(showItemHeight.value);
    }, 120);
};
watchEffect(() => {
    // 宽度
    // console.log(width.value);
    if (width.value) {
        nextTick(() => {
            isSmallHandle();
        });
    }
});

// 选择全部数据
const searchAllData = ()=>{
    // changeCrumb({title:'全部'},0)
    // tabPosition.value ="all"
    // tabChangeTypeFn({target:{id:'0'}})
}

// 点击左侧栏目树
const selectTree = (selectedKeys: any, e: any) => {
    /*
    searchRef.value?.clearInput()
    // 如果不是文件夹tab，需要定位到全部
    if( tabPosition.value != 'folder'){
     tabPosition.value = 'all';
    }
    tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = "";
    tabsTable.value[Number(currentTabIndex.value)].searchObj["mainType"] = 0;
    breadCrumb.value = [{ title: "全部", file_id: null }];
    if (e.selected) {
        currentTypeId.value = {
            media_resource_id: e.node.id,
            ...e.node
        }
        useFileInfo.setDirectoryId( e.node.id);
        initDataFn({ media_resource_id: e.node.id })
        if (!e.parent) e.parent = e.node.parent
        const arrList = getBreadCrumbByTree(e, [])
        breadCrumb.value = breadCrumb.value.concat(arrList.reverse())
    } else {
        useFileInfo.setDirectoryId("0");
        initDataFn(1)
    }
    */
}


// 操作成功回调
const SuccessfuCallbackFn = () => {
    /*
    tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = '';
    state.checkedList = [];
    similarityFlag.value = false;
    (document.getElementById("admin-page") as any).scrollTop = 0;
    breadMoveCrumb.value = [{ title: "全部", file_id: null }];
    if (currentTypeId.value == "") {
        initDataFn(1);
    } else {
        // 有子目录状态1
        initDataFn(currentTypeId.value);
    }
    */
};

const handNameFn = (item: any) => {
    /*
    filterFlag.value = false;
    selectName.value = item.media_resource_id;
    selectItem.value = "";
    selectItemName.value = item.title;
    selectItemObj.value = item;
    dialogVisibleName.value = true;
    */
};

// 新建监听   isTreeAdd表示是否左侧树里面的新增
const parentChang = (res: string,newFileObj?:any) => {
    /*
    tabPosition.value = 'all';
    if (res == 'folder-success' && useFileInfo.directory_id == '0') {
        tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = "";
        initDataArr.value = [];
        initDataFn(1);
    } else {
        tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = "";
        initDataArr.value = [];
        initDataFn(currentTypeId.value);
    }
    filterFlag.value = false;
       // 新增完，更新左侧对应树
    if(newFileObj){
        refreshTreAdd(newFileObj)
    }
 */
};

// 设置树状选中高亮状态
const setSelectedKeys = (item?: any) => {
    sideTreeRef.value?.setSelectedKeys(item)
}
// 删除左侧树的时候，判断右侧面包屑和内容是否要更新
const handleTreeDelete = (item:any)=>{
    /*
    const _o = breadCrumb.value.find(v=>{
        return item.id == v.media_resource_id
    })
    if(_o){
        // 删除的文件面包屑中有的时候
        tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = "";
        breadCrumb.value = [{ title: "全部", file_id: null }];
        initDataFn(1)
    }else{
        //  过滤掉删除的数据
        initDataArr.value = initDataArr.value.filter(v=>{
        return v.media_resource_id !=item.id
        })
    }
    */
}
// 移动左侧树时候，，判断右侧面包屑和内容是否要更新
const handleTreeMove = async (item:any) => {
    /*
    const _o = breadCrumb.value.find(v=>{
        return item.id == v.media_resource_id
    })
    // 联动了
    if(_o){
        backStore.netdiskObj.currentTypeId = {media_resource_id:item.id}
        await backStore.setBreadCrumbById()
        breadCrumb.value = backStore.netdiskObj.breadCrumb;
        initDataFn(backStore.netdiskObj.currentTypeId);
    }else{
        //  过滤掉移动掉的数据
        initDataArr.value = initDataArr.value.filter(v=>{
        return v.media_resource_id !=item.id
        })
    }
    */
}

// 更新左侧树的重命名
const refreshTreeName = (item: any) => {
    sideTreeRef.value?.refreshTreeName(item)
}
// 更新左侧树的新增
const refreshTreAdd = (item: any) => {
    // sideTreeRef.value?.refreshTreAdd(item)
    resetTreeData()
}
// 更新左侧树的删除
const refreshDeleteData = (item: any) => {
    // sideTreeRef.value?.refreshDeleteData(item)
    resetTreeData()
}
// 更新左侧树的移动
const refreshTreeMoveData = (item: any) => {
    // sideTreeRef.value?.refreshTreeMoveData(item)
    resetTreeData()
}
// 一些批量操作的，触发左侧树全量更新，
const resetTreeData = () =>{
    sideTreeRef.value?.resetTreeData()
}
</script>
<style scoped lang="scss" src="../MediaIndex/Index.scss"></style>
<style scoped lang="scss" src="../MediaDetail/index.scss"></style>
<style scoped lang="scss" src="./index.scss"></style>
